package com.mcjtf.prefix.listener;

import com.mcjtf.prefix.PrefixManager;
import com.mcjtf.prefix.api.event.PrefixChangeEvent;
import com.mcjtf.prefix.model.User;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;

public class PrefixListener implements Listener {
    private final PrefixManager plugin;

    public PrefixListener() {
        this.plugin = PrefixManager.getInstance();
    }

    @EventHandler
    public void onPrefixChange(PrefixChangeEvent event) {
        User user = plugin.getPrefixService().getUser(event.getPlayer().getName());
        if (user.getDisplayName().length() <= 16) {
            event.getPlayer().setPlayerListName(user.getDisplayName());
        }
    }

    @EventHandler(priority = EventPriority.HIGHEST)
    public void onPlayerChat(AsyncPlayerChatEvent event) {
        Player p = event.getPlayer();
        if (!plugin.getPrefixService().getUserMap().containsKey(p.getName())) {
            plugin.getPrefixService().loadPlayer(p.getName());
            return;
        }
        User user = plugin.getPrefixService().getUser(p.getName());
        String msg = event.getMessage();
        String format = null;
        if (plugin.format.containsKey(user.getGroup().toLowerCase())) {
            format = plugin.format.get(user.getGroup().toLowerCase());
        } else {
            format = plugin.format.get("default");
        }
        format = format.replaceAll("\\[DISPLAYNAME]", user.getDisplayName());
        format = format.replaceAll("\\[GROUP]", plugin.getVaultHook().getGroup(p));
        format = format.replaceAll("\\[G_PREFIX]", plugin.getVaultHook().getGroupPrefix(plugin.getVaultHook().getGroup(p), p.getWorld().getName()));
        format = format.replaceAll("\\[G_SUFFIX]", plugin.getVaultHook().getGroupSuffix(plugin.getVaultHook().getGroup(p), p.getWorld().getName()));
        format = format.replace('&', '§');
        if (p.hasPermission("essentials.msg.color") || p.hasPermission("prefixmanager.msg.color")) {
            msg = msg.replace('&', '§');
        } else {
            msg = msg.replace('§', ' ');
        }
        format = format.replaceAll("\\[MESSAGE]", msg);

        if (plugin.getPlaceholderHook() != null) {
            format = plugin.getPlaceholderHook().setPlaceholders(p, format);
        }
        format = format.replace("%", "");
        event.setFormat(format);
    }
}
